package dao

import (
	"gitee.com/huangxinbo/xcas/internal/app/base"
	"gitee.com/huangxinbo/xcas/internal/model/db_model"
	"github.com/gin-gonic/gin"
)

const (
	StorageTypeLocal = 1
	StorageTypeOSS   = 2
	StorageTypeCOS   = 3
	StorageTypeOBS   = 4
	StorageTypeBOS   = 5
	StorageTypeS3    = 6
	StorageTypeAzure = 7
	StorageTypeQiniu = 8
	StorageTypeGCS   = 9
	StorageTypeMinIO = 10
)

type FileDAO struct {
	base *base.Base
}

func NewFileDAO(base *base.Base) *FileDAO {
	return &FileDAO{
		base: base,
	}
}

// CreateFile creates a new file record
func (dao *FileDAO) CreateFile(ctx *gin.Context, file *db_model.File) error {
	return dao.base.Db.WithContext(ctx).Create(file).Error
}

// GetFileByID retrieves a file by ID
func (dao *FileDAO) GetFileByID(ctx *gin.Context, id string) (*db_model.File, error) {
	var file db_model.File
	err := dao.base.Db.WithContext(ctx).Where("id = ?", id).First(&file).Error
	if err != nil {
		return nil, err
	}
	return &file, nil
}

// DeleteFile soft deletes a file by ID
func (dao *FileDAO) DeleteFile(ctx *gin.Context, id string) error {
	return dao.base.Db.WithContext(ctx).Where("id = ?", id).Delete(&db_model.File{}).Error
}

// ListFiles retrieves files with pagination
func (dao *FileDAO) ListFiles(ctx *gin.Context, offset, limit int) ([]db_model.File, int64, error) {
	var files []db_model.File
	var total int64

	// Get total count
	if err := dao.base.Db.WithContext(ctx).Model(&db_model.File{}).Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// Get files with pagination
	err := dao.base.Db.WithContext(ctx).Offset(offset).Limit(limit).Order("created_at DESC").Find(&files).Error
	if err != nil {
		return nil, 0, err
	}

	return files, total, nil
}
